let products = [
    {id:1,name:"匹克筋膜枪",price:80.90,image:"https://gw.alicdn.com/imgextra/i1/2210261439061/O1CN012P7wn12GnzmSjsmRz_!!2210261439061.jpg",intro:"六档智能变速/黑色款"},
    {id:2,name:"运动护目镜",price:93.00,image:"https://gw.alicdn.com/imgextra/i3/761847617/O1CN019RYG5R268dPPSlT5F_!!761847617.jpg",intro:"运动透气/灰色框/透明镜片"},
    {id:3,name:"荣耀熊猫2025款平板电脑",price:1088,image:"https://gw.alicdn.com/imgextra/i2/2218748440207/O1CN01yKYMrd1DOr1dCLJNm_!!2218748440207.png",intro:"8核CPU/8GB内存/256GB SSD/RTX 3060Ti/144Hz屏"},
    {id:4,name:"NIKEDUNK LOW-IB3079",price:899,image:"https://gw.alicdn.com/imgextra/i2/890482188/O1CN01cAf9Uo1S29caeAQx3-890482188.jpg",intro:"鞋码: 45  颜色分类: 黑曜石/白/浅烟灰"}
]

/*
1.渲染界面
2.更新页面
3.增加商品（在增加数据时，需要判断是否已经存在该商品，如果存在则数量加一，如果不存在则添加一条新的商品）
4.删除商品(批量删除)
5.搜索商品（将搜索框内的内容映射到数组中，同时搜索的时候只出现一件商品，而删掉搜索框内的内容后再呈现所有的商品）
6.更改商品数量
7.计算总价

8.全选按钮
9.初始化全选按钮
10.更新全选按钮
11.初始渲染
12.购物车变化监听
13.结算按钮
14.搜索框
15.添加商品
*/

//渲染商品列表
function renderProductList(){
    const productList = document.getElementById("product-list")
    productList.innerHTML = ""

    if(products.length === 0){
        productList.innerHTML = `
        <div class = "noneProduct">
            <i class = fas fa-shopping-basket></i>
            <p>购物车空空如也</p>
        </div>
        `
        document.getElementById('select-all-checkbox').checked = false
        return
    }

    products.forEach(product => {
        const shoppingProduct = document.createElement("div")
        shoppingProduct.className = "product"
        shoppingProduct.dataset.id = product.id
        shoppingProduct.innerHTML = `
        <div class = "prodect-showing">
            <input type = "checkbox" id = "product-${product.id}" class="product-checkbox">
        </div>
        <div class = "product-image-container">
            <img src = "${product.image}" alt = "${product.name}">
        </div>
        <div class = "product-main-info">
            <div class = "product-name">${product.name}</div>
            <div class = "product-price">${product.price.toFixed(2)}</div>
        </div>
        <div class = "product-intro-container">
            <div class = "product-intro">${product.intro}</div>
        </div>
        <div class = "product-actions">
            <div class = "product-quantity">
                <input id = "quantity-${product.id}" type = "number" value = "1" min = "1">
            </div>
            <button class = "btn btn-delete" data-id = "${product.id}">
                <i class = "fas fa-trash-alt"></i>
            </button>
        </div>
        `

        productList.appendChild(shoppingProduct)

        // 在 renderProductList 函数中添加：
        const quantityInput = shoppingProduct.querySelector(`#quantity-${product.id}`)
        quantityInput.addEventListener('change', () => {
            product.num = parseInt(quantityInput.value)
            updateProductList()
        })

        // 商品复选框事件
        const productCheckbox = shoppingProduct.querySelector('.product-checkbox')
        productCheckbox.addEventListener('change',function(){
            updateSelectAllState()
            updateProductList()
        })

        //删除按钮
        const deleteButton = shoppingProduct.querySelector(".btn-delete")
        deleteButton.addEventListener("click", () => deleteFromProductList(product.id))
    })

    updateSelectAllState()
}

//更新商品列表
function updateProductList(){
    cart = []
    let numOfProduct = 0
    products.forEach(product => {
        const quantityInput = document.getElementById(`quantity-${product.id}`)
        const checkbox = document.getElementById(`product-${product.id}`)

        if(checkbox && checkbox.checked){
            const num = parseInt(quantityInput.value)
            cart.push({
                id:product.id,
                name:product.name,
                price:product.price,
                image:product.image,
                intro:product.intro,
                num:num
            })
            numOfProduct += num
        }
    })

    document.getElementById("selected-count").innerText = `已选择${numOfProduct}件商品`
    calculateTotalPrice()
    updateSelectAllState()
}

//计算总价
function calculateTotalPrice(){
    const moneyOfTotalProduct = cart.reduce((sum,product) => sum + product.price * product.num,0)
    document.getElementById("total-price").innerText = `总价:￥${moneyOfTotalProduct.toFixed(2)}`
}

//删除单个商品
function deleteFromProductList(productId){
    const index = products.findIndex(product => product.id === productId)
    if(index !== -1){
        products.splice(index,1)
        renderProductList()
        updateProductList()
    }
}

//批量删除
function deleteProducts(){
    const productsToDelete = []
    products.forEach(product => {
        const checkbox = document.getElementById(`product-${product.id}`)
        if(checkbox && checkbox.checked){
            productsToDelete.push(product)
        }
    })

    productsToDelete.forEach(product => {
        deleteFromProductList(product.id)
    })

    if(productsToDelete.length > 0){
        const batchDeleteBtn = document.getElementById('batch-delete-btn')
        batchDeleteBtn.querySelector('.batch-delete-icon').style.display = 'none';
        batchDeleteBtn.querySelector('.batch-delete-icon').classList.remove('active');
        batchDeleteBtn.querySelector('.batch-delete-text').classList.remove('active');
    }
}
// 批量删除按钮点击事件
let isBatchDeleteMode = false
document.getElementById('batch-delete-btn').addEventListener('click',function() {
    if(!isBatchDeleteMode){
        // 进入批量删除模式
        isBatchDeleteMode = true
        const deleteIcon = this.querySelector('.batch-delete-icon')
        const deleteText = this.querySelector('.batch-delete-text')
        deleteIcon.style.display = 'inline-block'
        deleteIcon.classList.add('active')
        deleteText.classList.add('active')
        // 显示所有复选框
        document.querySelectorAll('.product-checkbox').forEach(checkbox => {
            checkbox.style.visibility = 'visible'
        })
    }
    else{
        // 执行批量删除
        const selectedProducts = []
        document.querySelectorAll('.product-checkbox:checked').forEach(checkbox => {
            selectedProducts.push(parseInt(checkbox.id.split('-')[1]))
        })

        if(selectedProducts.length > 0){
            // 优化删除逻辑：过滤掉被选中的商品
            products = products.filter(product => 
                !selectedProducts.includes(product.id)
            )
            renderProductList()
            updateProductList()
        }

        // 退出批量删除模式
        isBatchDeleteMode = false
        const deleteIcon = this.querySelector('.batch-delete-icon')
        const deleteText = this.querySelector('.batch-delete-text')
        deleteIcon.style.display = 'none'
        deleteIcon.classList.remove('active')
        deleteText.classList.remove('active')
    }
})

//添加商品
document.getElementById('add-product-btn').addEventListener('click',function(){
    window.open("https://www.taobao.com", "_blank")
})

//搜索商品
document.addEventListener('DOMContentLoaded',function() {
    renderProductList()

    const searchInput = document.querySelector('.search-input')
    const searchBtn = document.querySelector('.search button')
    
    searchBtn.addEventListener('click', handleSearch)
    searchInput.addEventListener('input', handleSearch)
})

//搜索函数
function handleSearch(){
    const searchTerm = document.getElementById('search-input').value.trim().toLowerCase()
    const filtered = products.filter(p => p.name.toLowerCase().includes(searchTerm))
    products = filtered.length > 0 ? filtered : [...products]
    renderProductList()
}

//全选按钮
document.getElementById('select-all-checkbox').addEventListener('change',function(){
    const isChecked = this.checked
    document.querySelectorAll('#product-list input[type="checkbox"]').forEach(checkbox => {
        checkbox.checked = isChecked
    })
    updateProductList()
})

//更新全选按钮
function updateSelectAllState(){
    const checkboxes = document.querySelectorAll('.product-checkbox')
    const allChecked = checkboxes.length > 0 && [...checkboxes].every(checkbox => checkbox.checked)
    document.getElementById('select-all-checkbox').checked = allChecked
}

//初始化渲染界面
renderProductList()

//购物车变化监听
document.addEventListener('change',(e) => {
    if(e.target.matches('input[type = "checkbox"]') || e.target.matches('input[type = "number"]')){
        updateProductList()
    }
})

//结算按钮
let balance = 1500
let cart = []
// 修改结算按钮选择器
document.querySelector('.checkout').addEventListener('click', function(){ // 改为类选择器
    if(cart.length === 0){
        alert('购物车为空，请添加商品')
        return
    }
    
    // 生成结算信息
    let outPut = '<strong>您购买了以下商品：</strong><br>'
    let totalPrice = 0
    cart.forEach(product => {
        const productTotal = product.price * product.num
        outPut += `${product.name} × ${product.num} = ￥${productTotal.toFixed(2)}<br>`
        totalPrice += productTotal
    })
    
    // 显示结算弹窗
    showCheckoutModal(outPut, totalPrice)
})

// 显示结算弹窗函数
function showCheckoutModal(content, totalPrice){
    const modal = document.getElementById('checkout-modal')
    const modalContent = document.getElementById('checkout-content')
    const confirmBtn = document.getElementById('confirm-checkout')
    const cancelBtn = document.getElementById('cancel-checkout')
    // 设置内容
    modalContent.innerHTML = content
    // 显示弹窗
    modal.style.display = 'block'
    // 确认支付按钮事件
    confirmBtn.onclick = function(){
        if(balance >= totalPrice){
            // 支付成功后跳转
            window.open("checkout-success.html","_blank")
            // 清空购物车
            cart = []
            products = products.filter(p => !cart.some(c => c.id === p.id))
            renderProductList()
            updateProductList()
            modal.style.display = 'none'
        } 
        else {
            // 余额不足
            modalContent.innerHTML = `
                <div style="text-align:center;padding:20px 0;">
                    <i class="fas fa-times-circle" style="font-size:48px;color:#f44336;"></i>
                    <h3>支付失败</h3>
                    <p>余额不足！</p>
                    <p>当前余额：￥${balance.toFixed(2)}</p>
                    <p>还需：￥${(totalPrice - balance).toFixed(2)}</p>
                </div>
            `
            // 修改按钮
            confirmBtn.textContent = '确定'
            cancelBtn.style.display = 'none'
            
            confirmBtn.onclick = function() {
                modal.style.display = 'none'
                // 重置按钮状态
                cancelBtn.style.display = 'inline-block'
                confirmBtn.textContent = '确定支付'
            }
        }
    }
    // 取消按钮事件
    cancelBtn.onclick = function() {
        modal.style.display = 'none'
    }
    // 点击弹窗外部关闭
    window.onclick = function(event) {
        if (event.target == modal) {
            modal.style.display = 'none'
        }
    }
}